#include "command.h"

void handle_ls(char *cur_path, data *msg, int socket_fd){

    if (msg->args[0] == '\0') { // 检查 args 是否为空
        // 若args为空即只输入ls命令
        strcpy(msg->args, cur_path); // 用 cur_path 填充 args
    }
    if(msg->args[0] == '/'){
        // ls + 从根目录开始的客户端绝对路径
        // args以 "/" 开头不进行更改
    }
    else{
        // 此时余下的情况为输入命令 "ls"
        // 同时输入 以当前路径下文件夹开头的路径
        char path[3072] = {0};
        strncat(path, cur_path, sizeof(path) - strlen(path) - 1);
        if(strcmp(cur_path, "/") != 0){
            strncat(path, "/", sizeof(path) - strlen(path) - 1);
        }
        strncat(path, msg->args, sizeof(path) - strlen(path) - 1);
        strcpy(msg->args, path);
    }

    // 将 data 结构体发送到 socket
    ssize_t sent = send(socket_fd, msg, sizeof(data), 0);
    if (sent < 0) {
        perror("send failed in handler_send_ls");
    }

    data recv_ls;
    bzero(&recv_ls.args, sizeof(recv_ls.args));
    ssize_t received = recv(socket_fd, recv_ls.args, sizeof(recv_ls.args), MSG_WAITALL);
    if (received < 0) {
        perror("recv failed");
    } else if (received == 0) {
        printf("Server closed the connection\n");
    } else {
        // 打印接收到的数据
        printf("%s\n", recv_ls.args);
    }
}